const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('数据库连接成功'))
    .catch(err => console.log(err, '数据库连接失败'))

//创建集合规则
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
    email: String,
    password: String,
    hobbies: [String]
});

//使用规则创建集合
const User = mongoose.model('User', userSchema);

// User.create({
//     name: '邓明星',
//     age: 25,
//     email: '503120673@qq.com',
//     password: '201530135050',
//     hobbies: ['singing', 'read', 'play LOL']
// }).then(result => console.log(result))
//     .catch(err => console.log(err))

//查询用户集合中的所有文档
//User.find().then(result => console.log(result));

//返回数组
//User.find({ name: '霍雨浩' }).then(result => console.log(result));

//返回对象，默认第一条
//User.findOne({ name: '邓建' }).then(result => console.log(result));

//年龄大于20小于30
//User.findOne({ age: { $gt: 20, $lt: 30 } }).then(result => console.log(result))

//$in包含
//User.find({ hobbies: { $in: ['play LOL'] } }).then(result => console.log(result))

//加-标识不想查询的字段
//User.find().select('name age -_id').then(result => console.log(result))

//升序排列，加-变成降序
//User.find().sort('age').then(result => console.log(result))
//User.find().sort('-age').then(result => console.log(result))

//User.find().skip(1).limit(1).then(result => console.log(result))

//User.updateOne({ name: '霍雨浩' }, { name: '浩浩' }).then(result => console.log(result))
//User.updateMany({}, { age: 23 }).then(result => console.log(result))